package org.example.nio;
import org.example.util.ByteBufferUtil;
import org.example.util.PathUtil;
import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.Set;

/**
 * The type Nio example.
 */
public class ChannelExample {

    private PathUtil pathUtil = new PathUtil();
    /**
     * channel
     */
    @Test
    public void ChannelTest()throws Exception{
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("a.txt");
        ReadableByteChannel fileChannel = Channels.newChannel(inputStream);
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (fileChannel.read(byteBuffer) > 0) {
            // flip the buffer to prepare for get operation
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                ByteBufferUtil.debugAll(byteBuffer);
                System.out.println((char) byteBuffer.get());
            }
        }
        inputStream.close();
    }

    @Test
    public void FileChannelTest()throws Exception{
        //append the content to existing file
        writeFileChannel(ByteBuffer.wrap("Welcome to TutorialsPoint".getBytes()));
        //read the file
        readFileChannel();
    }

    public  void readFileChannel() throws IOException {
        // 获取文件的相对路径
        String relativePath = "temp.txt";
        // 获取文件的绝对路径
        String absolutePath = pathUtil.getAbsolutePath(relativePath);
        // 创建一个 RandomAccessFile 对象，用于读取文件
        RandomAccessFile file = new RandomAccessFile(absolutePath, "rw");
        // 获取文件通道
        FileChannel channel = file.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        Charset charset = Charset.forName("US-ASCII");
        while (channel.read(byteBuffer) > 0) {
            byteBuffer.rewind();
            System.out.print(charset.decode(byteBuffer));
            byteBuffer.flip();
        }
        channel.close();
    }
    public  void writeFileChannel(ByteBuffer byteBuffer)throws IOException {
        Set<StandardOpenOption> options = new HashSet<>();
        options.add(StandardOpenOption.CREATE);
        options.add(StandardOpenOption.APPEND);
        String relativePath = "temp.txt";
        // 获取文件的绝对路径
        String absolutePath = pathUtil.getAbsolutePath(relativePath);
        Path path = Paths.get(absolutePath);
        FileChannel fileChannel = FileChannel.open(path, options);
        fileChannel.write(byteBuffer);
        fileChannel.close();
    }
}
